<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2021-03-15 16:16:00
 * @Description: 管理员登录
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-04-21 16:03:32
 * @FilePath: /CoinCMF/app/Http/Controllers/Console/LoginController.php
 */

namespace App\Http\Controllers\Console;

use App\Customize\Func;
use App\Customize\Sign;
use App\Models\Rbac\Admin;
use App\Models\Rbac\RoleAdmin;
use App\Models\Rbac\RolePermission;
use App\Exceptions\FireFlyException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Ums\LoginRequest;

class LoginController extends Controller
{
    public function postLogin(LoginRequest $request)
    {
        // 先验证签名
        $res = Sign::aes_decrypt($request->all());
        if ($res['code'] != 200) {
            throw new FireFlyException(403, $res['message']);
        }
        $username = $request->input('name');
        $pwd = $request->input('password');
        $user = Admin::where('name', $username)->where('status', 1)->where('del_flag', 0)->first();
        if (is_null($user)) {
            throw new FireFlyException(400, '用户不存在或被禁用');
        }
        if ($user->password != Func::makepwd($pwd, $user->crypt)) {
            throw new FireFlyException(400, '密码不正确');
        }
        // 更新一些信息
        Admin::where('id', $user->id)->update(['lasttime' => date('Y-m-d H:i:s'), 'lastip' => $request->ip()]);
        $allRole = RoleAdmin::where('admin_id', $user->id)->pluck('role_id')->unique()->toArray();
        if ($user->id == 1) {
            $allRole[] = 1;
        }
        $allPermission = RolePermission::whereIn('role_id', $allRole)->pluck('label')->unique()->toArray();
        // 放到redis里边，先删除旧的，有效期一天
        $token = Func::getToken($user->name, 1);
        cache()->forget('c-token:' . $user->name);
        cache()->put('c-token:' . $user->name, json_encode(['id' => $user->id, 'phone' => $user->phone, 'name' => $user->name, 'allRole' => $allRole, 'allPermission' => $allPermission]), 3600 * 24);
        $res = ['id' => $user->id, 'name' => $user->name, 'token' => $token];
        return $this->resJson(200, '成功', $res);
    }
}
